package logic

import (
	"context"
	"io"
	"net/http"
	"os"
	"path"

	"imagesearch/internal/svc"
	"imagesearch/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

const maxFileSize = 10 << 20 // 10 MB

type ItemInfo struct {
	Id      string
	Name    string
	Des     string
	PicPath string
}

type AddItemLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	req    *http.Request
}

func NewAddItemLogic(req *http.Request, svcCtx *svc.ServiceContext) *AddItemLogic {
	return &AddItemLogic{
		Logger: logx.WithContext(req.Context()),
		svcCtx: svcCtx,
		req:    req,
	}
}

func (logic *AddItemLogic) AddItem() (resp *types.AddItemResponse, err error) {
	logic.req.ParseMultipartForm(maxFileSize)
	var name = logic.req.FormValue("name")
	var des = logic.req.FormValue("des")
	file, handler, err := logic.req.FormFile("picFileName")
	if err != nil {
		return nil, err
	}
	defer file.Close()

	logx.Infof("upload file: %+v, file size: %d, MIME header: %+v, Item name:%+v, Item description:%+v, config path::%+v",
		handler.Filename, handler.Size, handler.Header, name, des, logic.svcCtx.Config.Path)
	tmpFilePath := path.Join(logic.svcCtx.Config.Path, handler.Filename)
	tempFile, err := os.Create(tmpFilePath)
	if err != nil {
		return nil, err
	}
	defer tempFile.Close()
	io.Copy(tempFile, file)
	logx.Infof("File name:%+v", tempFile.Name())

	url, _ := PreserveImage(logic.svcCtx.Config.ImageConfig, tmpFilePath)

	var vearchConfig = logic.svcCtx.Config.VearchConfig
	var requestData VearchData
	requestData.IMG_URL = url
	requestData.ItemName = name
	requestData.Feature1.Feature = path.Join(vearchConfig.PluginPath, handler.Filename)
	var res = InsertToVearch(vearchConfig, requestData)
	if res != 0 {
		url = ""
	}
	return &types.AddItemResponse{
		Url: url,
	}, nil

}
